#include "udpsocket.h"
#include <QUdpSocket>
#include <cstdlib>
#include <stdio.h>
#include <QtNetwork/QNetworkInterface>
#include <QDebug>
#include "systemfile.h"
#include <QHostInfo>
#include <QProcess>
#define udp_send_port 5000
udpSocket::udpSocket(systemFile *point)
{
   this->sysInfo = point;
}

QString udpSocket::getIP()  //获取ip地址
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list)
    {
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
            //我们使用IPv4地址


            if (address.toString().contains("127.0."))
            {
                continue;
            }
       // qDebug() <<"IPV4 Address: "<< address.toString();
        //  Sys_Res.local_ip = address.toString();
        return address.toString();
    }
    return 0;
    //    QString localHostName = QHostInfo::localHostName();
    //    qDebug() <<"localHostName:"<<localHostName;
    //    QHostInfo info = QHostInfo::fromName(localHostName);
    //    foreach(QHostAddress address,info.addresses())
    //    {
    //        if(address.protocol() == QAbstractSocket::IPv4Protocol)
    //        qDebug() <<"IPV4 Address: "<< address.toString();
    //       return address.toString();
    //    }
    //        return 0;
}

QString udpSocket::getLocalIP()
{
    QProcess pro;
    QString udpdata;
    pro.start("ifconfig");
    pro.waitForFinished();
    QByteArray qba = pro.readAllStandardOutput();
    udpdata = QString::fromLocal8Bit(qba);
    return udpdata;
}

void udpSocket::udp_broadcast_reciver_data()
{
    QByteArray data;
    QByteArray askBuffer;
    QHostAddress sender;
    quint16 senderPort;
    QString udpdata;
    if(udpBroadLink->hasPendingDatagrams())
    {
        QString askStr;
        QString headStr;
        data.resize(udpBroadLink->pendingDatagramSize());
        udpBroadLink->readDatagram(data.data(),data.size(),&sender,&senderPort);
        QStringList list;
        QTextCodec *codec = QTextCodec::codecForName("GB2312"); //转化编码
        udpdata = codec->toUnicode(data);
        qDebug()<<"ip:"<<sender<<"port:"<<QString::number(senderPort)<<udpdata;
        //QString mnt=getLocalIP();
       // qDebug()<<"********"<<mnt;
        if(sender==QHostAddress(getIP()))
        {
           return;
        }
        //包头
        headStr = "::" + sysInfo->mac;
        sysInfo->localIp=getIP();
        list= udpdata.split(',');
        //广播地址
        if(list[0] == "::FF:FF:FF:FF:FF:FF" && list[1] == "FIND")
        {
            askStr = QString("%1,FIND,%2,%3,%4,%5\r\n").arg(headStr).arg("system").arg("system").arg(sysInfo->localIp).arg("system");
            askBuffer = codec->fromUnicode(askStr);
            udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress::Broadcast,udp_send_port);
            return;
        }
        else if(list[0] != headStr)
        {
            return;
        }

    }
}
